package com.winning.pmph.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.winning.pmph.entity.Rule;
import com.winning.pmph.entity.RuleItem;
import com.winning.pmph.mapper.RuleMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 刘亚飞
 * @Description
 * @create 2020-10-15 17:39
 */
@Component
@Transactional
public class RuleService extends ServiceImpl<RuleMapper, Rule> {

    @Resource
    private RuleMapper ruleMapper;
    @Resource
    private RuleItemService ruleItemService;

    public List<Rule> selectList() {
        List<Rule> ruleList = list();
        List<RuleItem> ruleItemList = ruleItemService.list();
        Map<String, List<RuleItem>> ruleItemMap = ruleItemList.stream().collect(Collectors.groupingBy(RuleItem::getRuleId));
        ruleList.forEach(item -> item.setRuleItemList(ruleItemMap.get(item.getId())));
        return ruleList;
    }

    public List<RuleItem> queryItemByRuleId(String ruleId) {
        return ruleItemService.lambdaQuery().eq(RuleItem::getRuleId, ruleId).orderByAsc(RuleItem::getIdx).list();
    }

    public List<RuleItem> queryItemByNameAndRuleId(String ruleId, String ruleItemName) {
        return ruleItemService.lambdaQuery().eq(RuleItem::getRuleId, ruleId).eq(RuleItem::getName, ruleItemName).orderByAsc(RuleItem::getIdx).list();
    }

    public void addRule(String ruleName, String ruleType, List<RuleItem> ruleItemList, String deletedOptions) throws Exception {
        String ruleId = ruleItemList.get(0).getRuleId();
        Rule rule;
        if (ruleId == null) {
            rule = new Rule();
        } else {
            rule = getById(ruleId);
        }
        rule.setName(ruleName);
        rule.setType(ruleType);
        saveOrUpdate(rule);

        // 删除数据
        JSONArray deletedOptionArray = JSONArray.parseArray(deletedOptions);
        deletedOptionArray.forEach(item -> {
            JSONObject optionJsonObject = (JSONObject) item;
            String id = optionJsonObject.getString("id");
            if (StringUtils.isNotBlank(id)) {
                ruleItemService.removeById(id);
            }
        });

        for (RuleItem ruleItem : ruleItemList) {
            ruleItem.setRuleId(rule.getId());
        }
        ruleItemService.saveOrUpdateBatch(ruleItemList);
    }
}
